package com.mamingchao.basic.observer;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by mamingchao on 2020/10/15.
 */
public class ObserverTester {

    public static void main(String[] args) {
        Child c = new Child();
        c.addListener(new Mom())
                .addListener(new Dad())
                .addListener(new Dog());
        c.wakeUp();

        System.out.println("-------------------------------------------------");

        WashingMachine wm = new WashingMachine();
        wm.addListener(new Mom())
                .addListener(new Dad())
                .addListener(new Dog());
        wm.doneWithWash();

    }


    /**
     * 所有事件生产者父类
     */
     static abstract class EventSource{
        String name;
        String sourceType;

        abstract EventSource getSource();

        List<Observer> observers = new ArrayList<>();

        EventSource addListener(Observer o) {
            this.observers.add(o);
            return this;
        }
    }

    /**
     * 其中一个事件生产者 孩子
     */
     static class Child extends EventSource{

        {
            sourceType = "child";
        }

        void wakeUp(){
            System.out.println("孩子醒了");
            Event e = new Event(this);
            for (Observer o: this.observers) {
                o.actionOnEvent(e);
            }
        }

        @Override
        EventSource getSource() {
            return this;
        }
    }
    /**
     * 其中一个事件生产者 洗衣机
     */
    static class WashingMachine extends EventSource{

        {
            sourceType = "washer";
        }

        void doneWithWash(){
            System.out.println("洗衣机洗完衣服了");
            for (Observer o: this.observers) {
                o.actionOnEvent(new Event(this));
            }
        }

        @Override
        EventSource getSource() {
            return this;
        }
    }

    /**
     * 所有观察者父类
     */
    static abstract class Observer{
        abstract void actionOnEvent(Event e);
    }

    static class Mom extends Observer{
        void hug(){
            System.out.println("妈妈抱一抱孩子");
        }

        @Override
        void actionOnEvent(Event e) {
            if (e.source.sourceType == "child") {
                hug();
            }
        }
    }

    static class Dad extends Observer{
        void HangClotherOut(){
            System.out.println("爸爸去晾衣服");
        }

        @Override
        void actionOnEvent(Event e) {
            if (e.source.sourceType == "washer") {
                HangClotherOut();
            }
        }
    }

    static class Dog extends Observer{

        void bark(){
            System.out.println("dog barked");
        }

        @Override
        void actionOnEvent(Event e) {
            if (e.source.sourceType == "child") {
                bark();
            }
        }
    }

    static class Event{
        EventSource source;

        public Event(EventSource source) {
            this.source = source;
        }
    }
}
